import time
from datetime import datetime
import requests
import pandas
import pandas as pd
import geopandas as geo
import matplotlib.pyplot as plt
from math import cos, sin, atan2, sqrt, pi, radians, degrees

requests.packages.urllib3.disable_warnings()  # 移除警告
# pandas show all rows
pd.set_option('display.max_rows', None)
# pandas show all col
pd.set_option('display.max_columns', 20)
# dataframe打印不换行
pd.set_option('display.width', 5000)


#####################################################
# 构建网格到网格的代价矩阵
# oId dId pubSign reTime carTime
#####################################################

def ptype(file):
    print(type(file))


def pd_show(file):
    print(file.shape)
    print(file.head(3))


def carTime(up_lon, up_lat, off_lon, off_lat):
    origin = str(up_lat) + ',' + str(up_lon)
    destination = str(off_lat) + ',' + str(off_lon)
    date = '2022-05-12T08:00:00'
    url = 'https://router.hereapi.com/v8/routes?apiKey=TyK6QDl8wb6kl6Gvv2ld86J7WZhqtarRFb4Hq-4rzKc&transportMode=car&origin=' + origin + '&destination=' + destination + '&avoid[features]=tollRoad&departureTime=' + date
    print(url)
    response = None
    # 用一个try except 来捕获请求的异常
    try:
        response = requests.get(url=url, headers=headers, verify=False).json()  # 获取HERE响应的路线json
    except:
        print('\033[31m错误:HERE API 请求发生错误\033[0m', url)
        response = {"notices": [
            {"title": "Routing is not possible due to missing transit information at this time", "code": "noCoverage"}],
            "routes": []}
    # 解析json
    routes = response.get('routes')  # 获取json中的路线集合
    print(response)
    # 如果有满足的路线就输出路线所需的时间，如果没有就输出-1
    carTime = None
    if len(routes) != 0:  # 如果路线集合!=0，说明有匹配的公共交通（地铁）线路
        sections = response.get('routes')[0].get('sections')  # sections是用户从a点到b点分段行驶路线的数组
        sectionSize = len(sections)
        userStartStr = sections[0].get('departure').get('time')[:-6].replace("T", " ")  # 用户出发的时间字符串
        userStopStr = sections[sectionSize - 1].get('arrival').get('time')[:-6].replace("T", " ")  # 用户到达目的地的时间字符串
        userStartTime = int(
            time.mktime(time.strptime(userStartStr, '%Y-%m-%d %H:%M:%S')))  # 将字符串格式化为时间戳，并转化为秒以便后续计算
        userStopTime = int(time.mktime(time.strptime(userStopStr, '%Y-%m-%d %H:%M:%S')))
        carTimeTemp = userStopTime - userStartTime  # 最终计算出用户从a点到b点驾驶汽车所需的时间秒
    print(carTimeTemp)
    return carTimeTemp


def reTime(up_lon, up_lat, off_lon, off_lat):
    origin = str(up_lat) + ',' + str(up_lon)
    destination = str(off_lat) + ',' + str(off_lon)
    date = '2022-05-12T08:00:00'
    url = 'https://transit.router.hereapi.com/v8/routes?apiKey=TyK6QDl8wb6kl6Gvv2ld86J7WZhqtarRFb4Hq-4rzKc&modes=bus,subway&origin=' + origin + '&destination=' + destination + '&departureTime=' + date
    print(url)
    response = None
    # 用一个try except 来捕获请求的异常
    try:
        response = requests.get(url=url, headers=headers, verify=False).json()  # 获取HERE响应的路线json
    except:
        print('\033[31m错误:HERE API 请求发生错误\033[0m', url)
        response = {"notices": [
            {"title": "Routing is not possible due to missing transit information at this time", "code": "noCoverage"}],
            "routes": []}
    print(response)
    subway = str(response).find('subway')
    bus = str(response).find('bus')
    transType = -1
    if subway != bus: transType = max(subway, bus)
    # 解析json
    routes = response.get('routes')  # 获取json中的路线集合

    # 如果有满足的路线就输出路线所需的时间，如果没有就输出-1
    reTimeTemp = None
    if len(routes) != 0:  # 如果路线集合!=0，说明有匹配的公共交通（地铁）线路
        sections = response.get('routes')[0].get('sections')  # sections是用户从a点到b点分段行驶路线的数组
        section_len = len(sections)
        userStartStr = sections[0].get('departure').get('time')[:-6].replace("T", " ")  # 用户出发的时间字符串
        userStopStr = sections[section_len - 1].get('arrival').get('time')[:-6].replace("T", " ")  # 用户到达目的地的时间字符串
        userStartTime = int(
            time.mktime(time.strptime(userStartStr, '%Y-%m-%d %H:%M:%S')))  # 将字符串格式化为时间戳，并转化为秒以便后续计算
        userStopTime = int(time.mktime(time.strptime(userStopStr, '%Y-%m-%d %H:%M:%S')))
        reTimeTemp = userStopTime - userStartTime  # 最终计算出用户从a点到b点乘坐地铁线路所需的时间秒

    print(reTimeTemp,transType)
    return {'reTimeTemp': reTimeTemp, 'transType': transType}  # 最终返回用户乘坐交通所需的时间


start = time.time()

# 构建请求头
headers = {
    # 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Mobile Safari/537.36'
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0'
}

# 读取站点信息
station = geo.read_file('../data/myz/res_station2.shp')
station.set_index(['id'], inplace=True)
pd_show(station)
columns = ['oId', 'dId', 'pubSign', 'carTime', 'reTime']
costMatrix = pd.DataFrame(columns=columns, data=None)
ids = station.index
oIds = []
dIds = []
for i in ids:
    for j in ids:
        if i != j:
            oIds.append(i)
            dIds.append(j)
costMatrix['oId'] = oIds
costMatrix['dId'] = dIds

pd_show(costMatrix)
print(costMatrix.head(10))

test = costMatrix[0:5]
print(test)
for index, row in test.iterrows():
    oId = row['oId']
    dId = row['dId']
    oRow = station.loc[oId]
    dRow = station.loc[dId]
    upLon = oRow['lon']
    upLat = oRow['lat']
    offLon = dRow['lon']
    offLat = dRow['lat']
    # print(oRow)
    # print(dRow)
    carTimeTemp = carTime(upLon, upLat, offLon, offLat)
    test.loc[index, 'carTime'] = carTimeTemp
    reTimeTemp = reTime(upLon, upLat, offLon, offLat)
    test.loc[index, 'reTime'] = reTimeTemp['reTimeTemp']
    pubSign = 1 if reTimeTemp['transType']!=-1 else 0
    test.loc[index, 'pubSign'] = pubSign

print(test)
# count program runtime
print('run time:', time.time() - start, 's')

# show draw board
plt.show()
